#!/usr/bin/python
# -*- coding: UTF-8 -*-


import re

import xlrd

import creat_excel_ios

# 生成新的语言包路径
new_strings_path = '../strings_new_ios.txt'


def read_excel():
    wb = xlrd.open_workbook(creat_excel_ios.save_excel_path)
    sheet = wb.sheet_by_name(creat_excel_ios.sheet_name)
    dict = {}
    for index in range(0, sheet.nrows):
        # print sheet.cell(index, 0).value
        # print sheet.cell(index, 1).value
        dict[sheet.cell(index, 0).value] = sheet.cell(index, 1).value
    return dict


def read_res():
    dict = read_excel()
    if len(dict) <= 0:
        return
    arry = []

    f = open(creat_excel_ios.string_file, encoding='utf-8')
    line = f.readline()
    while line:
        if line is not None and len(line) > 1:
            nameSearch = re.search(creat_excel_ios.pattern, line, 0)

            if nameSearch is None:
                # print nameSearch
                arry.append(line)
                line = f.readline()
                continue
            # print nameSearch

            if nameSearch.group(1) in dict:
                value = dict.get(nameSearch.group(1))
                newline = line.replace(re.search(creat_excel_ios.pattern, line, 0).group('value'), value, 1)
                print(newline)
                arry.append(newline)

        line = f.readline()
    f.close()
    return arry


def write_file(name='new_strings_ios.xml'):
    arry = read_res()
    with open(name, 'w', encoding='UTF-8') as f:
        in_arry = (line for line in arry)
        print(in_arry)
        f.writelines(in_arry)
    f.close()


def main():
    # read_excel()
    write_file(new_strings_path)


if __name__ == "__main__":
    main()
